package com.server.dao.impl;


import java.io.BufferedInputStream;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.Properties;







public class BasicDao {
     private String url="jdbc:mysql://localhost:3306/db_educate";
     private String user="root";
     private String password="a123";
     
     
     /**
      * 获得数据库连接对象
      * @return 数据库连接对象
     * @throws IOException 
      */
     private Connection getConnection() throws IOException{
		 InputStream in=new BufferedInputStream(new FileInputStream("src/com/util/db_connect.properties"));
    	 Properties prop=new Properties();
    	 prop.load(in);
    	 Connection conn=null;
    	 try {
			Class.forName("com.mysql.jdbc.Driver");
		    conn=DriverManager.getConnection(prop.getProperty("url"),prop.getProperty("user"),prop.getProperty("password"));
		} catch (ClassNotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
    	 return conn;
     }
     
     /**
      * 关闭数据库资源
      * @param rs 结果集对象
      * @param prs 操作对象
      * @param conn 连接对象
      * @throws SQLException
      */
     public void closeAll(ResultSet rs,PreparedStatement prs,Connection conn) throws SQLException{
    	 if(rs!=null){
    		rs.close(); 
    	 }else if(prs!=null){
    		 prs.close();
    	 }else{
    		 conn.close();
    	 }
     }
     
     /**
      * 数据库增删改操作
      * @param sql 增删改操作语句
      * @return 操作影响的行数
      */
     public int amdOpr(String sql){
     	
     	Connection conn = null;
		try {
			conn = getConnection();
		} catch (IOException e1) {
			// TODO Auto-generated catch block
			e1.printStackTrace();
		}
  		PreparedStatement prs=null;
  		int row = 0;
  			try {
 				prs = conn.prepareStatement(sql);
 				row=prs.executeUpdate(sql);
 				closeAll(null, prs, conn);
 			} catch (SQLException e) {
 				// TODO Auto-generated catch block
 				e.printStackTrace();
 			}
  		return row;
      }
     
     
     /**
      * 数据库查询操作
      * @param sql 查询语句
      * @return resultSet对象
     * @throws IOException 
      */
     public ResultSet query(String sql){
    	
    	Connection conn = null;
		try {
			conn = getConnection();
		} catch (IOException e1) {
			// TODO Auto-generated catch block
			e1.printStackTrace();
		}
 		PreparedStatement prs=null;
 		ResultSet rs=null;
 			try {
				prs = conn.prepareStatement(sql);
				rs=prs.executeQuery(sql);
				
			} catch (SQLException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
 		return rs;	
     }
 		

}
